package com.gzhryc.shared_device.oem.code.statistics.services;

import com.gzhryc.common.DateTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.oem.code.statistics.dao.PlaceUserProfitDayStatisticsDao;
import com.gzhryc.shared_device.oem.code.statistics.dao.db.PlaceUserProfitDayStatistics;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class PlaceUserProfitDayStatisticsService {

    static Logger log = Logger.getLogger(PlaceUserProfitDayStatisticsService.class);

    public static PlaceUserProfitDayStatisticsService self() {
        return MultiDBTools.getService(PlaceUserProfitDayStatisticsService.class, true);
    }

    public static PlaceUserProfitDayStatisticsService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, PlaceUserProfitDayStatisticsService.class, true);
    }

    PlaceUserProfitDayStatisticsDao dao;

    public PlaceUserProfitDayStatisticsService(String jdbcKey) {
        dao = new PlaceUserProfitDayStatisticsDao(jdbcKey);
    }

    public List<PlaceUserProfitDayStatistics> findByDayUserIdAndPlaceIds(Long userId, String dayDate, List<Long> placeIds){
        if(userId != null && StringTools.isNotBlank(dayDate) && placeIds != null && placeIds.size() > 0){
            Conditions conditions = new Conditions(PlaceUserProfitDayStatistics.class);
            conditions.and().is("userId",userId);
            conditions.and().is("dayDate",dayDate);
            conditions.and().in("placeId",placeIds);

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public PlaceUserProfitDayStatistics getOrAddByKeys(Long placeId, String placeName,String placeAreaName,Long userId,
                                                       String userName,String userPhone,Date createDate) {
        if (placeId != null && userId != null && createDate != null) {
            String dayDate = DateFormatUtils.format(createDate, "yyyyMMdd");
            Conditions conditions = new Conditions(PlaceUserProfitDayStatistics.class);
            conditions.and().is("placeId", placeId);
            conditions.and().is("userId", userId);
            conditions.and().is("dayDate", dayDate);
            try {
                PlaceUserProfitDayStatistics statistics = dao.get(conditions);
                if (statistics != null) {
                    return statistics;
                }else{
                    Integer yearNum = Integer.valueOf(DateFormatUtils.format(createDate, "yyyy"));
                    Integer monthNum = Integer.valueOf(DateFormatUtils.format(createDate, "MM"));
                    Integer dayNum = Integer.valueOf(DateFormatUtils.format(createDate, "dd"));
                    statistics = new PlaceUserProfitDayStatistics();
                    statistics.setPlaceId(placeId);
                    statistics.setPlaceName(placeName);
                    statistics.setPlaceAreaName(placeAreaName);
                    statistics.setUserId(userId);
                    statistics.setUserName(userName);
                    statistics.setUserPhone(userPhone);
                    statistics.setDayDate(dayDate);
                    statistics.setYearNum(yearNum);
                    statistics.setMonthNum(monthNum);
                    statistics.setDayNum(dayNum);
                    statistics.setCreateDate(createDate);

                    if (dao.insert(statistics) > 0) {
                        return statistics;
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public void addOneIncomeData(Long placeId,String placeName,String placeAreaName,Long userId,String userName,String userPhone
            ,Date divideDate, Long orderMoney, Long incomeMoney,Long refundMoney,Date refundDate) {
        PlaceUserProfitDayStatistics statistics = getOrAddByKeys(placeId,placeName,placeAreaName,userId, userName,userPhone,divideDate);
        if (statistics != null) {
            Conditions conditions = new Conditions(PlaceUserProfitDayStatistics.class);
            conditions.and().is("placeId", placeId);
            conditions.and().is("userId", userId);
            conditions.and().is("dayDate", statistics.getDayDate());

            if(refundMoney != null && refundDate != null){
                if(DateTools.isSameDay(divideDate,refundDate)) {
                    PlaceUserProfitDayStatistics updateEntity = new PlaceUserProfitDayStatistics();
                    updateEntity.setIncomeCount(1);
                    updateEntity.setIncomeMoney(incomeMoney);

                    try {
                        if (dao.updateNotNullAndInc(updateEntity, conditions, "incomeCount", "incomeMoney") > 0) {
                            updateEntity = new PlaceUserProfitDayStatistics();
                            updateEntity.setRefundCount(1);
                            updateEntity.setRefundMoney(refundMoney);
                            dao.updateNotNullAndReduce(updateEntity, conditions, "refundCount", "refundMoney");
                        }else{
                            log.error("修改网点用户收益统计(分成)失败，用户：{{0}}，时间：{{1}}", userId, divideDate);
                        }
                    } catch (SQLException e) {
                        log.error(e.getMessage(), e);
                    }
                }else{
                    PlaceUserProfitDayStatistics updateEntity = new PlaceUserProfitDayStatistics();
                    updateEntity.setIncomeCount(1);
                    updateEntity.setIncomeMoney(incomeMoney);

                    try {
                        if (dao.updateNotNullAndInc(updateEntity, conditions, "incomeCount", "incomeMoney") <= 0) {
                            log.error("修改网点用户收益统计(历史分成)失败，用户：{{0}}，时间：{{1}}", userId, divideDate);
                        }
                    } catch (SQLException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }else {
                PlaceUserProfitDayStatistics updateEntity = new PlaceUserProfitDayStatistics();
                updateEntity.setOrderMoney(orderMoney);
                updateEntity.setIncomeCount(1);
                updateEntity.setIncomeMoney(incomeMoney);

                try {
                    if (dao.updateNotNullAndInc(updateEntity, conditions, "orderMoney", "incomeCount", "incomeMoney") <= 0) {
                        log.error("修改网点用户收益统计(分成)失败，网点：{{0}}，用户：{{1}}，时间：{{2}}", placeId, userId, divideDate);
                    }
                } catch (SQLException e) {
                    log.error(e.getMessage(), e);
                }
            }
        } else {
            log.error("未找到或创建网点用户收益统计，网点：{{0}}，用户：{{1}}，时间：{{2}}", placeId, userId, divideDate);
        }
    }

    public void addOneRefundData(Long placeId,String placeName,String placeAreaName,Long userId,String userName,String userPhone
            ,Date refundDate,Long refundMoney,Date divideDate){
        PlaceUserProfitDayStatistics statistics = getOrAddByKeys(placeId,placeName,placeAreaName,userId, userName,userPhone,refundDate);
        if (statistics != null) {
            Conditions conditions = new Conditions(PlaceUserProfitDayStatistics.class);
            conditions.and().is("placeId", placeId);
            conditions.and().is("userId", userId);
            conditions.and().is("dayDate", statistics.getDayDate());

            if (DateTools.isSameDay(refundDate, divideDate)) {
                PlaceUserProfitDayStatistics updateEntity = new PlaceUserProfitDayStatistics();
                updateEntity.setRefundCount(1);
                updateEntity.setRefundMoney(refundMoney);

                try {
                    if (dao.updateNotNullAndInc(updateEntity, conditions, "refundCount", "refundMoney") > 0) {
                        updateEntity = new PlaceUserProfitDayStatistics();
                        updateEntity.setIncomeCount(1);
                        updateEntity.setIncomeMoney(refundMoney);
                        dao.updateNotNullAndReduce(updateEntity, conditions, "incomeCount", "incomeCount");
                    }else{
                        log.error("修改网点用户收益统计(退款)失败，网点：{{0}}，用户：{{1}}，时间：{{2}}", placeId, userId, refundDate);
                    }
                } catch (SQLException e) {
                    log.error(e.getMessage(), e);
                }
            }else{
                PlaceUserProfitDayStatistics updateEntity = new PlaceUserProfitDayStatistics();
                updateEntity.setHistoryRefundCount(1);
                updateEntity.setHistoryRefundMoney(refundMoney);

                try {
                    if (dao.updateNotNullAndInc(updateEntity, conditions, "historyRefundCount", "historyRefundMoney") <= 0) {
                        log.error("修改网点用户收益统计(历史退款)失败，网点：{{0}}，用户：{{1}}，时间：{{2}}", placeId, userId, refundDate);
                    }
                } catch (SQLException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }else {
            log.error("未找到或创建网点用户收益统计，网点：{{0}}，用户：{{1}}，时间：{{2}}", placeId, userId, refundDate);
        }
    }
}
